package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.TreeProblem;

/**
 * https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
 * <p>
 * 树转为链表, 使用right指针连接, 前序遍历(root在最前)
 *
 * @author tzp
 * @since 2020/10/13
 */
public class LC114 implements TreeProblem {
    public static class Pair<A, B> {
        public A a;
        public B b;

        public Pair(A a, B b) {
            this.a = a;
            this.b = b;
        }
    }

    public void flatten(TreeNode root) {
        if (root == null) return;
        rec(root);
    }


    //返回头和屁股
    public Pair<TreeNode, TreeNode> rec(TreeNode root) {
        if (root == null) return null;
        TreeNode end = root;
        if (root.left == null && root.right == null) {
            //do nth
        } else if (root.right != null && root.left != null) {
            Pair<TreeNode, TreeNode> leftResult = rec(root.left);
            Pair<TreeNode, TreeNode> rightResult = rec(root.right);
            root.right = leftResult.a;
            leftResult.b.right = rightResult.a;
            end = rightResult.b;
        } else {
            Pair<TreeNode, TreeNode> tmpResult = root.left == null ?
                    rec(root.right) : rec(root.left);
            root.right = tmpResult.a;
            end = tmpResult.b;
        }
        root.left = null;
        return new Pair<>(root, end);
    }

    public static void main(String[] args) {
        Integer[] a = {1, 2, 4, 3, 5, 7, 10, 6, null, 8, null, 11, 9, 15, null, null, null, 12, null, null, null, 13, null, null, null, null, 14};
        TreeNode treeNode = TreeNode.arrayToTreeNode(a);
        new LC114().flatten(treeNode);
        System.out.println(treeNode);
    }
}
